<template>
  <div class="sys-wrap">

    <div v-if="showPage == 1">
      <div class="msg-box" v-if="infoList.length != 0">
        <span class="info">未读消息{{infoNum}}条</span>
        <span class="manage" @click="manage">{{title}}</span>
      </div>

      <!--消息列表-->
      <div class="sys-van" :class="{'distance':showManage}" ref="wrapper" v-if="showData == 1">
        <div class="sys-box">
          <div class="sys-con" v-for="(item,index) in infoList" :key="index" @click="queryMsgDetail(item.id)">
            <div class="list-box">
              <div class="mui-input-row mui-checkbox select" v-if="single">
                <input name="checkbox" type="checkbox" :value="item.id">
              </div>
              <div class="icon-box" v-else>
                <img :src="item.status == 0?require('./msg1.png'):require('./msg2.png')" class="icon"
                     onclick="return false"/>
              </div>

              <div class="content-box">
                <span class="title">{{item.informationTitle}}</span>
                <span class="content">{{item.informationDetails}}</span>
              </div>
              <div class="time-box">{{item.time | format}}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="empty-wrap" v-if="showData == 2">
        <div class="empty-box">
          <div class="img-box"><img src="../../../assets/img/empty.png" class="empty" onclick="return false"/></div>
          <div class="tip">暂无新的消息~</div>
        </div>
      </div>

      <div class="btn-box" v-show="showManage">
        <div class="title1" @click="checkFull">
          <div class="mui-input-row mui-checkbox select">
            <input name="checkbox" type="checkbox" ref="all">
          </div>
          <span class="btn-title">全选</span>
        </div>


        <span class="select-num" v-show="number">已选{{number}}条</span>

        <button class="btn-cancel" @click="abrogateMsg">取消</button>
        <button class="btn-del" @click="delMsg">删除</button>
      </div>
    </div>

    <empty v-if="showPage == 2"></empty>


    <back-page @backPage="back" v-show="!showModal && !countentPhone"></back-page>

    <!--微信绑定手机号-->
    <v-phone v-model="showModal" @bindPhone="bindCustomerPhone"></v-phone>

  </div>
</template>

<script>
  import {baseUrl} from "../../../config/env";
  import {formatDate, getDeviceRatio, getSessionStore, getUrlKey, setSessionStore} from "../../../config/util"
  import backPage from "../../../components/backpage"
  import phone from "../../../components/phone"
  import BScroll from 'better-scroll'
  import empty from "../../../components/errorpage"

  /*获取当前缩放比*/
  const DEVICE_RATIO = getDeviceRatio();
  /**
   *
   * @param threshold 触发事件的阀值，即滑动多少距离触发
   */
  /*上拉配置*/
  const UP_CONFIG = {
    threshold: -80 * DEVICE_RATIO,
  }

  export default {
    inject: ['reload'],
    data() {
      return {
        infoNum: "",
        showSelect: false,
        flag: true,
        showManage: false,
        title: "管理",
        userSign: "",
        currentPage: 1,
        PageSize: 20,
        infoList: [],
        single: false,
        infoScroll: null,
        noMoreData: false,
        number: "",
        checked: true,
        allMsgNum: "",
        status: "",
        showModal: false,
        countentPhone: "",
        showData: 0,
        showPage: 0
      }
    },
    mounted() {
      this.userSign = getUrlKey("success"); //微信openid
      this.countentPhone = getUrlKey("countentPhone"); //手机框 0弹出1不弹出
      let base64 = require('js-base64').Base64;
      if (this.userSign != "" && this.userSign != "null" && this.userSign != null) {
        setSessionStore("success", base64.encode(this.userSign));
        this.userSign = base64.decode(getSessionStore("success"));
      } else {
        this.userSign = base64.decode(getSessionStore("success"));
      }

      if (this.countentPhone == "0") {
        this.showModal = true;
      } else {
        this.queryResidentAuth();
      }
    },
    methods: {
      queryResidentAuth() {//是否驻厂权限
        let time = (new Date()).getTime();
        let url = baseUrl + "/resident/get_resident_role?timestamp=" + time;
        let param = {"sgin": this.userSign, "timestamp": time};
        let signature = this.$signature(url, param);

        this.axios.get(baseUrl + "/resident/get_resident_role?sgin=" + this.userSign + "&type=" + "&auth=" + signature + "&timestamp=" + time).then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0 && resultObj.data == 1) {
            this.showPage = 1;
            this.queryMsgList();
            this.queryMsgNum();
            this.queryAllMsg();
          } else {
            this.showPage = 2;
          }
        }).catch(() => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      queryMsgList() {//查询消息列表
        this.axios.get(baseUrl + "/info/query_infolist?sgin=" + this.userSign + "&page=" + this.currentPage + "&size=" + this.PageSize).then((res) => {
          let infoObj = res.data;
          if (infoObj.code == 0) {
            if (infoObj.data != null && infoObj.data.length > 0) {
              let array = new Array();
              for (let i = 0; i < infoObj.data.length; i++) {
                if (infoObj.data[i].type == 1) {
                  array.push(infoObj.data[i]);
                }
              }

              if (array.length > 0) {
                this.infoList = array;
                this.selectAll("checkbox", false);
                this.$refs.all.checked = false;
                this.number = "";
                this.showData = 1;

                this.$nextTick(() => {
                  this.initScroll();
                  this.infoScroll.on('touchEnd', (pos) => {
                    if (Math.abs(Math.round(pos.y)) > Math.abs(Math.round(this.infoScroll.maxScrollY + 1))) {
                      this.loadMore();
                    }
                  });
                });
              } else {
                this.showData = 2;
                this.showManage = false;
                this.title = "管理";
              }
            } else {
              this.showData = 2;
              this.showManage = false;
              this.title = "管理";
            }
          } else {
            this.$vux.toast.text(infoObj.msg, "middle");
          }
        }).catch(() => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      queryMsgDetail(id) {//消息详情
        if (!this.showManage) {
          this.$router.push({path: "/msgdetail", query: {id: id}});
        } else {
          this.singleCheck();
        }
      },
      checkFull() {//全选
        if (this.flag) {
          this.selectAll('checkbox', true);
          this.flag = false;
          this.status = 1;
          this.number = this.allMsgNum;
        } else {
          this.selectAll('checkbox', false);
          this.flag = true;
          this.status = "";
          this.number = "";
        }
      },
      singleCheck() {//单选
        let allBox = document.getElementsByName('checkbox');
        let checkBox = this.getCheckBoxRes('checkbox');
        if (checkBox.length == allBox.length - 1) {
          this.$refs.all.checked = true;
        } else {
          this.$refs.all.checked = false;
        }
        this.number = checkBox.length;
      },
      manage() {//管理
        this.showSelect = true;
        this.showManage = true;
        this.title = "";
        this.single = true;
        this.$refs.all.checked = false;
      },
      abrogateMsg() {//取消
        this.showSelect = false;
        this.showManage = false;
        this.title = "管理";
        this.single = false;
        this.number = "";
      },
      delMsg() {
        let checkList = this.getCheckBoxRes('checkbox');
        if (checkList.length < 1) {
          this.$vux.toast.text("请选择要删除的消息", "middle");
          return;
        }
        this.$vux.loading.show({
          text: '加载中',
        });
        this.axios.get(baseUrl + "/info/del_infos?sgin=" + this.userSign + "&infoId=" + checkList + "&status=" + this.status).then((res) => {
          let infoObj = res.data;
          this.$vux.loading.hide();
          if (infoObj.code == 0 && infoObj.data != 0) {
            this.reload();
          } else {
            this.$vux.toast.text(infoObj.msg, "middle");
          }
        }).catch(() => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      getCheckBoxRes(className) {//选择checkbox
        let rdsObj = document.getElementsByName(className);
        let checkVal = new Array();
        let k = 0;
        for (let i = 0; i < rdsObj.length; i++) {
          if (rdsObj[i].checked) {
            if (rdsObj[i].value != "on") {
              checkVal[k] = parseInt(rdsObj[i].value);
            }
            k++;
          }
        }
        return checkVal;
      },
      selectAll(className, flag) {//全选/全不选
        let loves = document.getElementsByName(className);
        for (let i = 0; i < loves.length; i++) {
          loves[i].checked = flag;
        }
      },
      back() {
        this.$router.push('/residentIndex');
      },
      queryMsgNum() {//查询消息未读数
        this.axios.get(baseUrl + "/info/query_unreadNum?sgin=" + this.userSign + "&type=1").then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0 && resultObj.data != null) {
            this.infoNum = resultObj.data;
          } else {
            this.$vux.toast.text(resultObj.msg);
          }
        });
      },
      queryAllMsg() {//查询所有消息
        this.axios.get(baseUrl + "/info/query_unreadNum?sgin=" + this.userSign + "&status=1").then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0 && resultObj.data != null) {
            this.allMsgNum = resultObj.data;
          } else {
            this.$vux.toast.text(resultObj.msg);
          }
        });
      },
      bindCustomerPhone(phone) {//绑定微信客户手机号
        this.$vux.loading.show({
          text: '加载中',
        });

        let time = (new Date()).getTime();
        let url = baseUrl + "/wx_user/set_phone?timestamp=" + time;
        let param = {"sgin": this.userSign, "timestamp": time};
        let signature = this.$signature(url, param);

        //绑定微信手机
        this.axios.get(baseUrl + "/wx_user/set_phone?sgin=" + this.userSign + "&phone=" + phone + "&userName=" + "&userUrl=" + "&auth=" + signature + "&timestamp=" + time).then((res) => {
          let resultObj = res.data;
          this.$vux.loading.hide();
          if (resultObj.code == 0 && resultObj.data == 1) {
            this.queryResidentAuth();
          } else {
            this.showModal = true;
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch(() => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      loadMore() {//加载更多
        if (!this.noMoreData) {
          this.$vux.loading.show({
            text: '加载中',
          });
          setTimeout(() => {
            this.axios.get(baseUrl + "/info/query_infolist?sgin=" + this.userSign + "&page=" + (++this.currentPage) + "&size=" + this.PageSize).then((res) => {
              let infoObj = res.data;
              if (infoObj.code == 0) {
                if (infoObj.data != null && infoObj.data.length > 0) {
                  this.infoList = this.infoList.concat(infoObj.data);
                } else {
                  this.noMoreData = true;
                }
                this.$vux.loading.hide();
              } else {
                this.$vux.loading.hide();
                this.$vux.toast.text(infoObj.msg, "middle");
              }
            })
          }, 500);
        }
      },
      initScroll() {//初始化BScroll
        if (!this.infoScroll) {
          this.infoScroll = new BScroll(this.$refs.wrapper, {
            probeType: 3,
            deceleration: 0.003,
            bounce: false,
            swipeTime: 2000,
            click: true,
            pullUpLoad: UP_CONFIG
          });
        } else {
          this.infoScroll.refresh();
        }
      },
      enable() {
        this.infoScroll && this.infoScroll.enable()
      },
      refresh() {
        this.infoScroll && this.infoScroll.refresh()
      },
      finishPullUp() {
        this.infoScroll && this.infoScroll.finishPullUp()
      }
    },
    filters: {
      format(time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd');
      },
    },
    watch: {
      infoList() {
        this.$nextTick(() => {
          this.infoScroll.refresh();
        })
      }
    },
    components: {
      "v-phone": phone,
      backPage,
      BScroll,
      empty
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../assets/stylus/mixin.styl"
  @import "../../../../static/mui.min.css"

  .sys-wrap
    wh(100%, 100%)
    .msg-box
      fj(space-between, center)
      position: fixed
      top: 0
      z-index: 99
      wh(100%, 0.8rem)
      background: #f2f2f2
      .info
        margin-left: 0.32rem
        size-color(0.347rem, rgba(153, 153, 153, 1))
      .manage
        position: absolute
        right: 0.373rem
        size-color(0.347rem, rgba(60, 175, 255, 1))
    .sys-van
      position: fixed
      top: 0.8rem
      bottom: 0
      wh(100%, auto)
      .sys-box
        wh(100%, auto)
        .sys-con
          display: flex
          align-items: center
          margin-left: 3.2%
          wh(96.8%, 1.813rem)
          border-bottom: 0.027rem solid #f2f2f2
          &:last-child
            border-bottom: none
          .list-box
            display: flex
            align-items: center
            wh(96.8%, 1.813rem)
            .icon-box
              margin-right: 0.32rem
              wh(0.747rem, 0.747rem)
              .icon
                wh(100%, 100%)
            .select
              display: flex
              align-items: center
              margin-right: 0.32rem
              wh(0.507rem, 0.507rem)
            .time-box
              margin-left: auto
              size-color(0.32rem, rgba(153, 153, 153, 1))
              padding-bottom: 0.6rem
            .content-box
              display: flex
              flex-direction: column
              width: 58%
              .title
                padding-top: 0.06rem
                padding-bottom: 0.06rem
                ellipsis()
                size-color(0.427rem, rgba(29, 29, 29, 1))
              .content
                ellipsis()
                size-color(0.373rem, rgba(102, 102, 102, 1))
                padding-top: 0.12rem
    .empty-wrap
      fj(center, center)
      wh(100%, auto)
      position: fixed
      top: 0
      left: 0
      right: 0
      bottom: 0
      z-index: -1
      .empty-box
        wh(4.773rem, auto)
        .img-box
          wh(100%, 4.773rem)
          .empty
            wh(100%, 100%)
        .tip
          display: flex
          justify-content: center
          margin-top: 0.387rem
          size-color(0.373rem, rgba(68, 68, 68, 1))
    .distance
      padding-bottom: 1.44rem
    .btn-box
      display: flex
      align-items: center
      position: fixed
      bottom: 0
      wh(100%, 1.44rem)
      border-top: 1px solid rgba(227, 227, 227, 1)
      background: rgba(255, 255, 255, 1)
      .title1
        display: flex
        align-items: center
        .select
          display: flex
          align-items: center
          margin-left: 0.32rem
          margin-right: 0.32rem
          wh(0.507rem, 0.507rem)
        .btn-title
          margin-right: 0.293rem
          size-color(0.427rem, rgba(153, 153, 153, 1))
      .select-num
        size-color(0.427rem, rgba(60, 175, 255, 1))
      .btn-cancel
        margin-left: auto
        wh(2.4rem, 0.96rem)
        border: 0.027rem solid rgba(153, 153, 153, 1)
        border-radius: 0.16rem
        size-color(0.453rem, rgba(153, 153, 153, 1))
        line-height: 0.48rem
      .btn-del
        margin-left: 0.16rem
        margin-right: 0.32rem
        wh(2.4rem, 0.96rem)
        background: rgba(60, 175, 255, 1)
        border-radius: 0.16rem
        size-color(0.453rem, rgba(255, 255, 255, 1))
        line-height: 0.48rem
</style>
